package cn.bincker.test.service.impl;

import cn.bincker.test.entity.ClassRoom;
import cn.bincker.test.entity.Student;
import cn.bincker.test.mapper.first.StudentMapper;
import cn.bincker.test.mapper.second.ClassRoomMapper;
import cn.bincker.test.service.IStudentService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 手动事务
 */
@Service
public class ManualStudentServiceImpl implements IStudentService {
    private final StudentMapper studentMapper;
    private final ClassRoomMapper classRoomMapper;
    private final TransactionTemplate firstTransactionTemplate;
    private final TransactionTemplate secondTransactionTemplate;

    public ManualStudentServiceImpl(
            StudentMapper studentMapper,
            ClassRoomMapper classRoomMapper,
            TransactionTemplate firstTransactionTemplate,
            @Qualifier("secondTransactionTemplate") TransactionTemplate secondTransactionTemplate
    ){
        this.studentMapper = studentMapper;
        this.classRoomMapper = classRoomMapper;
        this.firstTransactionTemplate = firstTransactionTemplate;
        this.secondTransactionTemplate = secondTransactionTemplate;
    }

    @Override
    public Student addStudentToClassRoom(String studentName, String classRoomName) {
        return firstTransactionTemplate.execute((status -> secondTransactionTemplate.execute(status1 -> {
            ClassRoom classRoom = classRoomMapper.findByName(classRoomName);
            if (classRoom == null) {
                classRoom = new ClassRoom();
                classRoom.setName(classRoomName);
                classRoomMapper.insert(classRoom);
            }
            Student student = new Student();
            student.setName(studentName);
            student.setClassRoomId(classRoom.getId());
            studentMapper.insert(student);
            //noinspection ConstantConditions
            if (true) throw new RuntimeException();
            return student;
        })));
    }
}
